import { BehaviorSubject } from 'rxjs'

let onlineQ = true
import { webSocket } from 'rxjs/webSocket'
console.log('connect ws')
const ws = webSocket({
  url: onlineQ ? 'wss://web.gcs360.com/chat' : 'wss://web.gcs360.com/chat',
  openObserver: {
    next(t) {
      register()
      console.log('websocket opened.',t)
    }
  },
  closeObserver: {
    next() {
      console.log('websocket closed.')
    }
  }
})

/**
 * 从缓存中获取人才ID
 * @returns {string}
 */
function getTalentId() {
  const user = localStorage.getItem(localSaved.commTalentId)
  if (user) {
    return user;
  } else {
    return ''
  }
}

/**
 * 获取人才的图像
 * @returns {*}
 */
function getTalentIcon() {
  const user = localStorage.getItem(localSaved.userInfo)
  if (user) {
    const o = JSON.parse(user)
    if (o.image) {
      return o.image
    } else {
      return null
    }
  } else {
    return null
  }
}

/**
 * 注册websocket
 */
function register() {
  if (getTalentId()) {
    const o = {
      'mainCom': 'talent',
      'mainUserId': getTalentId(),
      'type': 'REGISTER'
    }
    console.log('websocket register', o)
    ws.next(o)
  }
}

/**
 * 取消注册websocket
 */
function offline() {
  const o = {
    'mainCom': 'talent',
    'mainUserId': getTalentId(),
    'type': 'REMOVE'
  }
  console.log('websocket offline', o)
  ws.next(o)
}

function getCompanyIcon(icon) {
  if (icon) {
    let fileName = icon.substring(icon.lastIndexOf('/') + 1, icon.indexOf('.'))
    return require('@/assets/img/setting/' + fileName + '.png')
  } else {
    return null
  }
}

const event = new BehaviorSubject(null)

export default {
  ws: ws,
  register: register,
  offline: offline,
  getTalentId: getTalentId,
  getCompanyIcon: getCompanyIcon,
  getTalentIcon: getTalentIcon,
  event: event
}